﻿using System;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using MovingBall;

namespace MovingBall_Sample
{
    public partial class BallsForm : Form
    {
        private readonly int _ballMinSize;
        private readonly int _ballMaxSize;
        private readonly Random _randomGen;

        public BallsForm()
        {
            InitializeComponent();
            _ballMinSize = 4;
            _ballMaxSize = 20;
            _randomGen = new Random();
        }

        private void PanelPlaygroundClick(object sender, EventArgs e)
        {
            PanelPlayground.Controls.Add(new Ball(
                Color.FromArgb(_randomGen.Next(255), _randomGen.Next(255), _randomGen.Next(255)),
                _randomGen.Next(_ballMinSize, _ballMaxSize), (MouseEventArgs)e));
        }

        private void ButtonClearBallsClick(object sender, EventArgs e)
        {
            ClearPlayground();
        }

        private void ButtonAddBallClick(object sender, EventArgs e)
        {
            PanelPlayground.Controls.Add(new Ball(
                Color.FromArgb(_randomGen.Next(255), _randomGen.Next(255), _randomGen.Next(255)),
                _randomGen.Next(_ballMinSize, _ballMaxSize), 
                _randomGen.Next(0, PanelPlayground.Width), 
                _randomGen.Next(0, PanelPlayground.Height)));
        }

        private void BallsFormFormClosing(object sender, FormClosingEventArgs e)
        {
            ClearPlayground();
            Environment.Exit(0);
        }

        private void ClearPlayground()
        {
            foreach (var control in PanelPlayground.Controls.OfType<Ball>().Where(control => control != null))
                control.IsEnd = true;
            PanelPlayground.Controls.Clear();
        }
    }
}
